package com.ndf.learn.controller;

import com.ndf.learn.verify.captcha.GifCaptcha;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.io.IOException;

/**
 * Explain:演示GIF验证码的控制器
 */
@Controller
public class GifCaptchaController {

    private Logger logger = LoggerFactory.getLogger(GifCaptchaController.class);

    @RequestMapping(value = {"/captcha"} , method = {RequestMethod.GET})
    public ModelAndView hello(HttpServletRequest request
            , HttpServletResponse response) throws Exception{
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg", "Hello World");
        mv.setViewName("captcha.jsp");
        return mv;
    }

    /**
     * 获取Gif验证码
     * @param response
     */
    @RequestMapping(value = "/gifCaptcha",method= RequestMethod.GET)
    public void getGifCaptcha(HttpServletResponse response,HttpServletRequest request){
        //告诉客户端，输出的格式
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/gif");
        GifCaptcha gifCaptcha =  new GifCaptcha(200,80,new Font("宋体", Font.BOLD, 40),100);
        try {
            gifCaptcha.out(response.getOutputStream());
            logger.info("获取验证码！验证码字符为："+gifCaptcha.getWord());
            HttpSession session = request.getSession(true);
            //存入Session
            session.setAttribute("captchaWord",gifCaptcha.getWord());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
